package com.business.file.controller.gen;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageInfo;
import com.business.system.common.base.BaseController;
import com.business.system.common.domain.AjaxResult;
import com.business.file.model.auto.TFile;
import com.business.system.model.custom.TableSplitResult;
import com.business.system.model.custom.Tablepar;
import com.business.system.model.custom.TitleVo;
import com.business.file.service.TFileService;
import io.swagger.annotations.Api;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

@Controller
@RequestMapping("TFileController")
@Api(value = "")
public class TFileController extends BaseController{

	public static String uploadPath="d:\\upload\\patrol";
	
	private String prefix = "gen/tFile";
	@Autowired
	private TFileService tFileService;
	
	@GetMapping("view")
    public String view(ModelMap model)
    {	
		String str="";
		setTitle(model, new TitleVo("列表", str+"管理", true,"欢迎进入"+str+"页面", true, false));
        return prefix + "/list";
    }
	
	//@Log(title = "集合查询", action = "111")
	@RequestMapping("list")
	@ResponseBody
	public Object list(Tablepar tablepar,String searchTxt){
		PageInfo<TFile> page=tFileService.list(tablepar,searchTxt) ; 
		TableSplitResult<TFile> result=new TableSplitResult<TFile>(page.getPageNum(), page.getTotal(), page.getList()); 
		return  result;
	}
	
	/**
     * 新增
     */

    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        return prefix + "/add";
    }
	
	//@Log(title = "新增", action = "111")
	@PostMapping("add")
	@ResponseBody
	public AjaxResult add(TFile tFile){
		int b=tFileService.insertSelective(tFile);
		if(b>0){
			return success();
		}else{
			return error();
		}
	}
	
	/**
	 * 删除
	 * @param ids
	 * @return
	 */
	//@Log(title = "删除", action = "111")
	@PostMapping("remove")
	@ResponseBody
	public AjaxResult remove(String ids){
		int b=tFileService.deleteByPrimaryKey(ids);
		if(b>0){
			return success();
		}else{
			return error();
		}
	}
	
	/**
	 * 检查
	 * @param
	 * @return
	 */
	@PostMapping("checkNameUnique")
	@ResponseBody
	public int checkNameUnique(TFile tFile){
		int b=tFileService.checkNameUnique(tFile);
		if(b>0){
			return 1;
		}else{
			return 0;
		}
	}
	
	
	/**
	 * 修改跳转
	 * @param id
	 * @param mmap
	 * @return
	 */
	@GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("TFile", tFileService.selectByPrimaryKey(id));

        return prefix + "/edit";
    }
	
	/**
     * 修改保存
     */
    //@Log(title = "修改", action = "111")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TFile record)
    {
        return toAjax(tFileService.updateByPrimaryKeySelective(record));
    }


	/**
	 * 文件上传 适用任何类型的文件
	 * @param request
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadFile")
	@ResponseBody
	public AjaxResult uploadFile(MultipartHttpServletRequest request){
		String message="";
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;
		String relativePath = "";
		while (itr.hasNext()) {
			mpf = request.getFile(itr.next());
			try {
				if (mpf.getSize() < 104857600*100) {
					String attachmentName = StringUtils.substringBeforeLast(
							mpf.getOriginalFilename(), ".");
					String ext = StringUtils.substringAfterLast(
							mpf.getOriginalFilename(), ".");
					ext = ext.toLowerCase();//转小写
					String fileName = UUID.randomUUID() + "." + ext;
					File realPath = new File(TFileController.uploadPath);
					if (!realPath.exists()) {
						realPath.mkdirs();
					}
					FileCopyUtils.copy(mpf.getBytes(),
							new File(realPath.getAbsolutePath() + "\\"
									+ fileName));
					TFile tfile=new TFile();
					tfile.setFileName(fileName);
					tfile.setFileType(ext);
					tfile.setCreateTime(new Date());
					tfile.setFilePath(realPath.getAbsolutePath() + "\\" + fileName);
					this.tFileService.insertSelective(tfile);
					return AjaxResult.success().put("file",tfile);
				} else {
					message = "文件太大，请不要 超过100M";
					return AjaxResult.error("文件太大，请不要 超过100M");
				}
			} catch (Exception e) {
				message = "上传失败";
				return AjaxResult.error( "上传失败");
			}
		}
		return AjaxResult.error();
	}


	/**
	 * 预览图片
	 *
	 * @throws IOException
	 * @throws Exception
	 */
	@GetMapping("tFile/preFile/{id}")
	public void prePhoto(@PathVariable String id, HttpServletResponse response) throws IOException {
		TFile file=this.tFileService.selectByPrimaryKey(id);
		if(file!=null){
			String filePath = file.getFilePath();
		}
		String filePath = file.getFilePath();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		OutputStream os = null;
		InputStream is = null;
		is = new FileInputStream(filePath);
		bis = new BufferedInputStream(is);
		os = response.getOutputStream();
		bos = new BufferedOutputStream(os);
		int byteRead = 0;
		byte[] buffer = new byte[5 * 1024];
		while ((byteRead = bis.read(buffer)) != -1) {
			bos.write(buffer, 0, byteRead);
		}
		bos.close();
		bis.close();
		os.close();
		is.close();
	}

	
}
